<template>
  <div class="login container">
    <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        autocomplete="off"
    >
      <h3 class="title" style="text-align: center">{{ title }}</h3>
      <el-form-item
          prop="username"
      >
        <el-input
            v-model="loginForm.username"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="请输入账号"
            :prefix-icon="User"
            clearable
        >
        </el-input>
      </el-form-item>
      <el-form-item
          prop="password"
      >
        <el-input
            class="password-input"
            v-model="loginForm.password"
            type="password"
            size="large"
            auto-complete="off"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            clearable
            show-password
        >
        </el-input>
      </el-form-item>
      <div class="captch-info">
        <el-form-item
            prop="code"
        >
          <el-input
              class="captch-form-item"
              v-model="loginForm.code"
              size="large"
              auto-complete="off"
              placeholder="请输入验证码"
              :prefix-icon="Lock"
              clearable
          >
          </el-input>
        </el-form-item>
        <!--   src赋值为绝对路径 会自动拼上当前网页的协议和域名组成完整的访问路径   -->
        <img ref="codeImg" style="width:110px;height: 42px" src="/api/account-platform/captcha/get" @click="getCaptchaReq" alt="">
      </div>
      <!--   提交按钮   -->
      <el-form-item>
        <el-button
            class="login-btn"
            size="large"
            type="primary"
            :loading="loading"
            @click="submitForm('loginForm')"
        >
          {{ loading ? '登录中' : '登录'}}
        </el-button>
      </el-form-item>
    </el-form>
    <div class="copy-right">Copyright ©2020-2024 开运科技 All Rights Reserved.</div>
  </div>
</template>

<!--引入icon就在setup里面处理-->
<script setup>
   // 引入icon （如果没有引入 可以注释）
   import { User, Lock } from '@element-plus/icons-vue';
</script>

<script>
/* eslint-disable */
import Cookies from 'js-cookie'
import {getUserInfo, login, oauthToken, unbindAccount} from "@/api/login";
import {setStorage, util} from "@/utils/util";

import preventBack from 'vue-prevent-browser-back';
import {getCodeImg} from "@/api/ky-api/ky-api";
import {apiManager} from "@/utils/apiManager";

export default {
  name: "webLogin",
  components:{

  },
  props:{

  },
  // 注入 阻止返回上一页
  mixins: [preventBack],
  data(){
    return {
      title: "数字管理平台",
      // 1快货运系统
      loginType:1,

      // 是否登录中
      loading:false,
      codeUrl: '/api/account-platform/captcha/get',
      // 表单绑定数据源
      loginForm: {
        username: "18575518001",
        password: "ssWLvlXz",
        rememberMe: false,
        code: "",
        uuid: "",
      },

      // 表单校验规格 对象形式
      loginRules: {
        // 对用户名进行校验 数组 一个输入框可以有多条校验规则
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
        ],
        code: [
            { required: true, trigger: "change", message: "请输入验证码" }
        ],
      },

      dialogVisible:true,
    }
  },
  created() {
  },
  mounted() {
    this.unbind()
    Cookies.set('captcha-id', '')
    if (this.loginType == 0) {
      this.getCookie()
    }
  },
  methods:{
    unbind() {

      if (this.loginType == 0) {
        const param = {
          loginName:'102742781'
        }
        unbindAccount(param).then(res => {
          // this.$message.success('解绑成功')
        }).catch(err => {
          // this.$message.error('解绑失败')
        })
      } else if (this.loginType == 1) {

        // getCodeImg().then(res => {
        //   console.log('获取开运系统验证码：', res)
        // }).catch(err => {
        //   console.log('获取开运系统验证码失败：', err)
        // })
      }
    },

    /**
     * 点击刷新图形验证码
     */
    getCaptchaReq() {
      this.$refs.codeImg.src = this.codeUrl
    },

    /**
     * 取cookie中存的用户名和密码赋值
     */
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      this.loginForm.username = username
      this.loginForm.password = password
    },

    /**
     * 表单提交
     * @param formName
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          this.loginReq()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    /**
     * 表单校验通过 执行登录
     */
    loginReq() {
      const { username, password, code } = this.loginForm

      let loginType = this.loginType;
      if (loginType == 1) {
        // 获取验证码图片时会在cookie里塞一个captchaId
        let captchaId = Cookies.get("captcha-id");
        if (!captchaId) {
          this.$message.warning('验证码已失效');
          this.loading = false;
          this.getCaptchaReq();
          return;
        }

        // 快货运系统登录
        let authInfo = {}
        authInfo.username = username
        authInfo.password = util.md5Str(password)
        authInfo.scope = 'web'
        authInfo.grant_type = 'password'
        authInfo.captcha = code
        authInfo.captchaId = captchaId
        console.log('快货运系统authInfo:', authInfo)

        oauthToken(authInfo).then(res => {
          this.loading = false;
          console.log('快货运系统登录信息验证完成：', res)
          this.authSuccess(res.data)
        }).catch(err => {
          this.loading = false;
          console.log('快货运系统登录信息验证失败')
          this.getCaptchaReq()

          // mock
          // let info = {
          //   'access_token':'abcd',
          //   'expires_in':24 * 60 *60,
          //   'refresh_token':'abcdefg',
          //   'token_type':'Bearer',
          // };
          // this.authSuccess(info)
        });
        return;
      }

      // 先从缓存中取设备号 - 登录成功过后本地记住了16位的uuid
      let uuid = util.getLocalStorage('uuid')

      if (uuid.length == 0) {
        uuid = util.getUuid()
        // 将字符串中的-全部替换为空字符
        uuid = uuid.replace(/-/g, '')
        // md5后 - 32位
        uuid = util.md5Str(uuid)
        // 取16位的md5
        uuid = uuid.substring(8, 24)
      }
      const pwd = util.md5Str(password)
      this.loginSuccess()
      return

      login(username, pwd, uuid).then(res => {
        this.loading = false
        console.log('登录成功', res)
        this.loginSuccess()
      }).catch(err => {
        console.log('登录失败', err)
        this.loading = false
        this.getCaptchaReq()
      })
    },

    /**
     * 快货运系统验证成功 - 标记认证key 认证类型 登录状态等信息
     */
    authSuccess(info) {
      // 认证通过后的认证key
      let access_token = info.access_token;
      // 有效时长
      let expires_in = info.expires_in;
      // 当token失效去拿新的token
      let refresh_token = info.refresh_token;
      // 头部认证key的类型 未登录Basic 登录后Bearer
      let tokenType = info.token_type
      setStorage('access_token', access_token, expires_in)
      setStorage('refresh_token', refresh_token)
      setStorage('tokenType', tokenType)
      this.$store.commit('SET_IS_LOGIN', true)
      this.$store.commit('SET_TOKEN', access_token)
      Cookies.set('token', 'isLogin')
      this.loginSuccess()
      // this.getKhyUserInfo()
    },

    /**
     * 快货运系统账号密码校验完成获取用户信息
     */
    getKhyUserInfo() {
      getUserInfo().then(res => {
        console.log('快货运获取用户信息成功：', res);
        this.loginSuccess(res.data);
      }).catch(err => {
        console.log('快货运获取用户信息失败：', err);
      })
    },

    loginSuccess(userInfo) {
      const { username, password } = this.loginForm

      // 更改登录标记
      Cookies.set('token', 'isLogin')
      Cookies.set('username', username)
      Cookies.set('password', password)
      this.$store.commit('SET_IS_LOGIN', true)
      // this.$router.push('/index')
      location.href = '/index';
    },
  }
}
</script>

<style scoped>

.container {
  min-height: 400px;
}

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-image: url("../assets/login-background.jpg");
  position: relative;
}

.copy-right {
  position: absolute;
  text-align: center;
  font-size: 14px;
  bottom: 0;
  height: 60px;
  line-height: 60px;
}

.login-form {
  border-radius: 6px;
  background: #ffffffcc;
  width: 400px;
  padding: 25px 25px 5px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  box-sizing: border-box;
}

.password-input {
  margin-top: 15px;
}

.captch-info {
  display: flex;
  justify-content: space-between;
}

.captch-form-item {
  width: 220px;
}

.login-btn {
  display: block;
  margin: 15px auto 0;
  width: 100%;
  align-items: center;
  align-content: center;
}

</style>
